package com.oa.configuration;

import com.oa.common.ComplexAccessDeniedHandler;
import com.oa.common.ComplexAuthenticationFailureHandler;
import com.oa.common.ComplexAuthenticationSuccessHandler;
import jk.framework.spring.security.SecuritySupport;
import jk.framework.spring.security.authorization.SecurityResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

/**
 * 安全配置
 *
 * @author
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecuritySupport support;
    @Autowired
    private UserDetailsService detailsService;
    @Autowired
    private SecurityResourcesService resourcesService;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        support.authenticationDetailsProvider(auth, detailsService, passwordEncoder);
    }


    /**
     * 动态权限配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {




        support.dynamicAuthorize(http)
                .resourcesService(resourcesService)
                .decisionManagerStrategy().affirmative()
                .anyRequest().authenticated();


        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.applyPermitDefaultValues();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);


        source.registerCorsConfiguration("/**", corsConfiguration);

        http.cors().configurationSource(source);

        http.csrf().disable();

        http.exceptionHandling().accessDeniedHandler(new ComplexAccessDeniedHandler());

        http.formLogin()
                .successHandler(new ComplexAuthenticationSuccessHandler())
                .failureHandler(new ComplexAuthenticationFailureHandler())
        ;
        //.failureHandler(null);
    }


}
